package com.chaoyi.util.qiniu;

import java.io.InputStream;
import javax.servlet.http.Part;
import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UploadFileQiNiu {
	private static Logger log =LoggerFactory.getLogger(UploadFileQiNiu.class);
	public static final String accessKey = "HqeuYJi7RXkAKA1SIxXXFmtWVE61A5XcAh5_e1hy";
	public static final String secretKey = "R9G6oRkDSI7Oo1TnnUMP9HYhT6-TBbX0DxiomTVW";
	public static final String bucket = "xz-web";
	public static final String fileUrl = "http://web.myche51.cn/";

	public static String uploadFile(Part uploadFile, String path, String fileName) throws Exception {
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone0());
		log.info(cfg.toString());
		// ...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		log.info(uploadManager.toString());
		// 默认不指定key的情况下，以文件内容的hash值作为文件名
		String key = path + fileName;
		log.info(key);
		InputStream fileContent = null;
		fileContent = uploadFile.getInputStream();
		Auth auth = Auth.create(accessKey, secretKey);
		log.info(auth.toString());
		String upToken = auth.uploadToken(bucket);
		log.info(upToken);
		Response response = uploadManager.put(fileContent, key, upToken, null, null);
		log.info("返回response="+response.toString());
		new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
		return fileUrl + path + fileName;
	}
}
